import { Command } from '@react-native-community/cli-types';
import os from 'node:os';
import fs from 'node:fs';
import pathUtils from 'node:path';

export const commandCreateMetroConstantsHarmony: Command = {
  name: 'create-metro-host-constants-harmony',
  description:
    'Creates a Typescript file that exports constant with IP of the host machine. That IP is later used to connect to the Metro server from a physical device.',
  options: [
    {
      name: '--output <string>',
      description: 'Output file',
      default: './harmony/entry/src/main/ets/codegen/MetroHostConstants.ts',
    },
  ],
  func: async (argv, config, args: any) => {
    createMetroHostConstants(pathUtils.resolve(args.output));
  },
};

function createMetroHostConstants(outputPath: string): void {
  const networkInterfacesByName = os.networkInterfaces();
  const getIP = () => {
    for (let name of Object.keys(networkInterfacesByName)) {
      for (let net of networkInterfacesByName[name] ?? []) {
        // skip over non-ipv4 and internal (i.e. 127.0.0.1) addresses
        if (net.family === 'IPv4' && !net.internal) {
          return net.address;
        }
      }
    }
    return;
  };
  const ip = getIP();
  const tsCode = [
    '// This file is autogenerated. Do not modify it manually.',
    '',
    `export const METRO_SERVER_IP = '${ip}';\n`,
  ];
  fs.writeFile(outputPath, tsCode.join('\n'), (err) => {
    if (err) {
      console.error(`Error writing to ${outputPath}:`, err);
    } else {
      console.log(`Created file at ${outputPath}`);
    }
  });
}
